'use strict';

const adminRouter = require('../controller/admin/router');
const passport = require('../middleware/passport');

const isLogin = (req, res, next) => {
	if (req.isAuthenticated()) {
  	next();
  } else {
  	res.redirect('/login');
  }
}


module.exports = function(app) {
	app.use('/admin', isLogin, adminRouter);
	app.get('/', function(req, res, next) {
	  if (req.isAuthenticated()) {
	  	res.render('index');
	  } else {
	  	res.redirect('/login');
	  }
	});

	app.get('/login', function(req, res, next) {
		res.render('login')
	})


	app.get('/logout', function(req, res, next) {
		req.logout();
    res.redirect('/');
	})

	app.post('/login', (req, res, next) => {
		passport.authenticate('local', (err, user, info) => {
	    if (err) { return next(err); }
	    if (!user) { return res.send({ iscorrect: false }); }
	    req.login(user, (errr) => {
	      if (errr) { return next(errr); }
	      return res.send({ iscorrect: true, username: user.username });
	    });
	  })(req, res, next);
	});
}